// @ts-nocheck
const {parse} = require('@babel/parser')

/**
 * 将数据格式化 
 */
function _normalizeData(properties) {
  let ret = {}
  properties.forEach(prop => {
    let key = prop.key.name
    ret[key] = prop
  })
  return ret
}
/**
 *  script 解析
 */
function parseScript(text) {
  let ast = parse(text, {sourceType: 'module', plugins:['jsx', 'flow']})
  let exp = ast.program.body.find(o => o.type === 'ExportDefaultDeclaration')
  if(exp) {
    let properties = exp.declaration.properties;
    let ret = {}
    properties.forEach(prop => {
      let key = prop.key.name
      let value;
      switch(key) {
        case 'data':
          value = prop.body.body[0].argument.properties
          ret[key] = _normalizeData(value)
          break
        case 'props':
        case 'computed':
        case 'methods':
          value = prop.value.properties
          ret[key] = _normalizeData(value)
          break
      }
    })
    return ret
  }
}

function isFile(line) {
  try{
    let ast = parse(line, {sourceType: 'module', plugins:['jsx', 'flow']})
    return ast.program.body[0].type === 'ImportDeclaration' || ast.program.body[0].declarations[0].init.body.callee.type === 'Import'
  } catch(e) {
    // console.log(e);
  }
  return false
  //ast.program.body[0].type === 'ImportDeclaration'
  //ast.program.body[0].declarations[0].init.body.callee.type === 'Import'
}

/**
 * 检查当前想要获取定义的类型，判断为文件、字段、方法
 */
function checkType(word, line) {
  // let propReg = new RegExp(`(((v-bind)?:[a-z]+)[ ]*=[ ]*["'][ ]*${word}[ ]*["'])`)
  // let methodReg = new RegExp(`(((v-on:)||@[a-zA-Z-]+)[ ]*=[ ]*["'][ ]*${word}[ ]*["'])`)
  // let pm = line.match(propReg)
  // let mm = line.match(methodReg)
  let fm = isFile(line)
  return fm ? 'file' : 'prop'
}

function getPosition(map, keys, word, m) {
  let pos = {x: 0, y: 0}
  for(let key of keys) {
    let o = map[key]
    if(o) {
      let k = Object.keys(o)
      if(k.includes(word)) {
        let tar = o[word]
        if(tar) {
          let index = m.index + m[1].length + tar.key.end
          let lines = m.input.substring(0, index).split('\n')
          let y = lines.length - 1
          let last = lines[y]
          let x = last.length - word.length
          pos = {x, y}
        }
      }
    }
  }
  return pos
}

module.exports = {
  parseScript,
  parse,
  checkType,
  getPosition
}